﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.UI;
using Grishko.DataTier;
using OutdoorLib.BaseEntity.Infrastructure;
using OutdoorLib.BaseEntity.Filters;
using OutdoorLib.BaseEntity.Contract;

namespace Grishko.UI
{
    /// <summary>
    /// Контрол отображающий сетку загрузки
    /// </summary>
    public class SideSheduleTable : Control, IListOfFilter
    {
        
        readonly String Cell_MainTable_Td_Css = "grd_td_item";
        readonly String Cell_MainTable_TdHeader_Css = "grd_td_head";
        readonly Unit[] CellSizes_DescribeTable = { new Unit("100px"), new Unit("200px"), new Unit("200px"), new Unit("50px") };
        readonly string[] CellData_DescribeTableHeader = { "Номер","Тип конструкции","Адрес","Цена"};
        readonly Unit CellSize_DescribeTable = new Unit("600px");

        

        /// <summary>
        /// ПАрамтры визуализации сетки загрузки - с какого по какое и с каким шагом
        /// </summary>
        public class SideSheduleParams
        {
            public DateTime dtStart { get; set; }
            public DateTime dtFinish{ get; set; }
            public Ecopsy.Tools.DateTimeTools.TimePeriod Period { get; set;}
            public ContractEntity   CurrentContract { get; set; }
        }
        /// <summary>
        /// Параметры визуализации
        /// </summary>
        public SideSheduleParams SheduleTimeParam {get; set;}

        public SideSheduleTable() { }

        private readonly string PageMethodFormatKey = "PageMethodFormat";
        
        /// <summary>
        /// Формат команды PageMewthod 
        /// </summary>
        public string PageMethodFormat
        {

            get
            {                
                object text = ViewState[PageMethodFormatKey];
                if (null == text)
                    return string.Empty;
                else
                    return (string)text;
            }
            set
            {                
                ViewState[PageMethodFormatKey] = value;
            }
        }

        /// <summary>
        /// Css строчки
        /// </summary>
        public string ItemCss { get; set; }

        //Открыть закрыть отображение элемента
        private bool bEnableRander = false;

        protected override void OnLoad(EventArgs e)
        {
        
        }

        

        protected override void Render(HtmlTextWriter writer)
        {
            if (this.DesignMode)
            {
                writer.Write("Сетка загрузки ");
                return;
            }

            //// прорисовываем только если есть источник
            if (null == DataSource)
                return;
            if (bEnableRander)
                MyRender(writer);

        }

        public override void DataBind()
        {
            bEnableRander = true;
        }

        private void MyRender(HtmlTextWriter writer)
        {
            if (null == DataSource())
                                return;

            ///Получить коллекцию данных из источника
            List<EntitySingle> RowDataList = DataSource().GetCollection();

            //Каркас. Каждая строка из 2 панелей. Первая панель - описание стороны - вторая расписание этой стороны 
            Table MainTable = new Table() { Width = new Unit("100%") };
            
            //Сформировать заголовок
            MainTable.Rows.Add(GetHeaderMainTableRow());
            
            //Заполнить табличку
            foreach (SheduleSideRow RowData in RowDataList)
            {
                TableRow MainTableRow = new TableRow();

                //// описание стороны
                Panel PnlSideDescribe = new Panel() { Width = CellSize_DescribeTable };
                PnlSideDescribe.Controls.Add(GetSideDescribeTable(RowData, CellSizes_DescribeTable));
 
                TableCell CellSideDescribe = new TableCell();
                CellSideDescribe.CssClass = Cell_MainTable_Td_Css;
                CellSideDescribe.Controls.Add(PnlSideDescribe);

                //// расписание стороны
                Panel PnlSideShedule = new Panel() { ID = "Shedule_" + RowData.SideEntity.ID };                

                TableCell CellSideShedule = new TableCell();
                CellSideShedule.CssClass = Cell_MainTable_Td_Css;
                
                ///Формируем контрол расписание стороны
                SideSheduleRow SheduleRow = new SideSheduleRow(RowData.Shedule, 
                                                               SheduleTimeParam, 
                                                               PageMethodFormat);
                PnlSideShedule.Controls.Add(SheduleRow);

                CellSideShedule.Controls.Add(PnlSideShedule);
                

                MainTableRow.Cells.Add(CellSideDescribe);
                MainTableRow.Cells.Add(CellSideShedule);

                MainTable.Rows.Add(MainTableRow);
            }
            MainTable.RenderControl(writer);
        }

        /// <summary>
        /// Вернуть заголовок 
        /// </summary>
        /// <returns></returns>
        private TableRow GetHeaderMainTableRow()
        {
            //Сформировать заголовок описания сторон           
            TableRow HeaderTableRow = new TableRow();
            Panel PnlHeaderTableRow = new Panel() { Width = CellSize_DescribeTable };
            PnlHeaderTableRow.Controls.Add(GetHeaderSideDescribeTable(CellData_DescribeTableHeader, CellSizes_DescribeTable));

            TableCell CellHeaderSideDescribe = new TableCell();
            CellHeaderSideDescribe.CssClass = Cell_MainTable_TdHeader_Css;
            CellHeaderSideDescribe.Controls.Add(PnlHeaderTableRow);

            HeaderTableRow.Cells.Add(CellHeaderSideDescribe);

            /// Заголовок расписания стороны
            SideSheduleRow SheduleRow = new SideSheduleRow(SheduleTimeParam, PageMethodFormat);
            TableCell CellHeaderSideShedule = new TableCell();
            CellHeaderSideShedule .Controls .Add (SheduleRow.GetHeaderRow());
            CellHeaderSideShedule.CssClass = Cell_MainTable_TdHeader_Css;
            HeaderTableRow.Cells.Add(CellHeaderSideShedule);

            return HeaderTableRow;
        }


        /// <summary>
        /// Вернуть табличку с описанием стороны
        /// </summary>
        /// <returns></returns>
        private Table GetSideDescribeTable(SheduleSideRow RowSource,Unit[] CellSizes )
        {

            Table tbl = new Table() { Width = new Unit("100%"), CellPadding = 0, CellSpacing = 2};
            TableRow rw = new TableRow();
            
            TableCell CellSideNumber = new TableCell();
            CellSideNumber.Width = CellSizes[0];
            CellSideNumber.Text = RowSource.Constraction.Number + RowSource.Litera;            
            rw.Cells.Add(CellSideNumber);

            TableCell CellSideType= new TableCell();
            CellSideType.Text = RowSource.Constraction.ConstractionTypeAsString;
            CellSideType.Width = CellSizes[1];
            rw.Cells.Add(CellSideType);

            TableCell CellSideAddress = new TableCell();
            CellSideAddress.Text = RowSource.Constraction.FullAdress ;
            CellSideAddress.Width = CellSizes[2];
            rw.Cells.Add(CellSideAddress);


            TableCell CellSidePrice = new TableCell();
            CellSidePrice.Text = RowSource.CurrentPrice .ToString ();
            CellSidePrice.Width = CellSizes[3];
            rw.Cells.Add(CellSidePrice);

            tbl.Rows.Add(rw);
            return tbl;

        }

        /// <summary>
        /// Вернуть табличку с описанием стороны
        /// </summary>
        /// <returns></returns>
        private Table GetHeaderSideDescribeTable(string[] HeaderData, Unit[] CellSizes)
        {
            Func< int,TableCell>PopulateCell=delegate (int CellNumber)
            {
                
            TableCell Cell= new TableCell();
            Cell.Width = CellSizes[CellNumber];
            Cell.Text = HeaderData[CellNumber];            
            return Cell;
            };

            Table tbl = new Table() { Width = new Unit("100%"), CellPadding = 0, CellSpacing = 0 };
            TableRow rw = new TableRow();

            for (int i = 0; i < HeaderData.Length; i++)
            {
                rw.Cells.Add(PopulateCell(i));
                
            }

            tbl.Rows.Add(rw);
            return tbl;

        }


        #region Члены IListOfFilter

        public Func<Filter> DataSource { get; set; }

        #endregion
    }

}
